//
//  QRCodeViewController.swift
//  HYYWeibo
//
//  Created by HY-Mac on 16/7/13.
//  Copyright © 2016年 HY-Mac. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {

    @IBOutlet weak var customContainerView: UIView!
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var scanLineConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var containerHeight: NSLayoutConstraint!
    @IBOutlet weak var customTabBar: UITabBar!
    

    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        customTabBar.selectedItem = customTabBar.items!.first
        customTabBar.delegate = self
        
        scanQRCode()

    }
    private func scanQRCode(){
        if !session.canAddInput(input){ return }
        if !session.canAddOutput(output){ return }
        
        session.addInput(input)
        session.addOutput(output)
        
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        previewLayer.frame = view.bounds
        
        view.layer.addSublayer(containerLayer)
        containerLayer.frame = view.bounds
        
        session.startRunning()
        
        
    }
    
    @IBAction func clostBtnClick(sender: AnyObject) {
        dismissViewControllerAnimated(true) { 
            
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        startAnimation()
        }
    
    private func startAnimation(){
        scanLineConstraint.constant = -containerHeight.constant
        view.layoutIfNeeded()
        UIView.animateWithDuration(1.5) {
        UIView.setAnimationRepeatCount(MAXFLOAT)
        self.scanLineConstraint.constant = self.containerHeight.constant
        self.view.layoutIfNeeded()
    }
    }
    //MARK: - 懒加载
    /// 输入对象
    private lazy var input:AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        return try? AVCaptureDeviceInput(device: device)
    }()
    ///会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    ///输出对象
    private lazy var output: AVCaptureMetadataOutput = {
        let viewRect = self.view.frame
        let out = AVCaptureMetadataOutput()
        let x: CGFloat = self.customContainerView.frame.origin.y / viewRect.height
        let y: CGFloat = self.customContainerView.frame.origin.x / viewRect.width
        let width = self.customContainerView.frame.height / viewRect.height
        let height = self.customContainerView.frame.width / viewRect.width
        out.rectOfInterest = CGRectMake(x, y, width, height)
        return out
    }()
    
    //预览图层
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    private lazy var containerLayer: CALayer = CALayer()
    
    @IBAction func photoBtnClick(sender: AnyObject) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){ return }
        let imagePickerVC = UIImagePickerController()
        
        imagePickerVC.delegate = self
        
        presentViewController(imagePickerVC, animated: true) { 
            
        }
        
        
        
    }
}
extension QRCodeViewController:  UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //HYLog(info)
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{ return }
        let ciImage = CIImage(image: image)
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil)
        
        let features: [CIFeature] = detector.featuresInImage(ciImage!)
        
        for feature in features{
            HYLog((feature as! CIQRCodeFeature).messageString)
        }
        
        picker.dismissViewControllerAnimated(true) { 
            
        }
        
    }
}


extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate{
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        clearLayers()
        resultLabel.text = metadataObjects.last?.stringValue
        guard let metadata = metadataObjects.last as? AVMetadataObject else { return }
        //HYLog(metadata)
        let obj = previewLayer.transformedMetadataObjectForMetadataObject(metadata)
        //HYLog((obj as! AVMetadataMachineReadableCodeObject).corners)
        drawResultRect((obj as! AVMetadataMachineReadableCodeObject))
    }

private func drawResultRect(obj: AVMetadataMachineReadableCodeObject){
    guard let array = obj.corners else { return }
    
    let layer = CAShapeLayer()
    layer.lineWidth = 2
    layer.fillColor = UIColor.clearColor().CGColor
    layer.strokeColor = UIColor.greenColor().CGColor
    
    let path = UIBezierPath()
    var point = CGPointZero
    var index = 0
    CGPointMakeWithDictionaryRepresentation(array[index++] as! CFDictionary, &point)
    path.moveToPoint(point)
    while index < array.count {
        CGPointMakeWithDictionaryRepresentation(array[index++] as! CFDictionary, &point)
        path.addLineToPoint(point)
    }
    path.closePath()
    layer.path = path.CGPath
    containerLayer.addSublayer(layer)
}
    private func clearLayers(){
        guard let sublayers = containerLayer.sublayers else{ return }
        for layer in sublayers{
            layer.removeFromSuperlayer()
        }
    }
}



extension QRCodeViewController: UITabBarDelegate{
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        containerHeight.constant = (item.tag == 1) ? 150: 250
        view.layer.removeAllAnimations()
        startAnimation()
    }
}


